class_name Player
extends CharacterBody2D 

# --------------------变量声明----------------------#
@onready var playerAni=$AnimatedSprite2D
@onready var stats=$Stats

const KNOCKBACK_AMOUNT:=2000

var dir:=Vector2.ZERO
var canMove=false
var stop=false

var attacks:=[]
var hurting:=false
# --------------------生命周期----------------------#
func _ready() -> void:
	choosePlayer('player1')
	pass

func _input(event: InputEvent) -> void:
	if event is InputEventMouseButton and event.button_index==MOUSE_BUTTON_LEFT and event.is_pressed():
		canMove=true
	if event is InputEventMouseButton and event.button_index==MOUSE_BUTTON_LEFT and !event.is_pressed():
		canMove=false

func _physics_process(delta: float) -> void:
	if stats.hp==0:
		return die()
	move(delta)
	if attacks.size()!=0 and !hurting:
		getHurt()
	pass

# --------------------函数调用----------------------#
# 加载动画
func choosePlayer(type)->void:
	var path='res://资源/角色/玩家/'

	playerAni.sprite_frames.clear_all()

	var sprite=SpriteFrames.new()
	sprite.add_animation('idle')
	sprite.set_animation_loop('idle',true)
	
	var textureSize=Vector2(960,240)
	var spriteSize=Vector2(240,240)
	var texture:Texture=load(path+type+'-sheet.png')

	var columns=int(textureSize.x/spriteSize.x)
	var rows=int(textureSize.y/spriteSize.y)

	for y in range(rows):
		for x in range(columns):
			var frame=AtlasTexture.new()
			frame.atlas=texture
			frame.region=Rect2(Vector2(x,y)*spriteSize,spriteSize)
			sprite.add_frame('idle',frame)
	playerAni.sprite_frames=sprite
	playerAni.play('idle')
	pass

# 移动
func move(_delta):
	var mousePos=get_global_mouse_position()
	dir=(mousePos-position).normalized()
	playerAni.flip_h=dir.x<0
	if canMove and !stop:
		velocity=dir*stats.speed
		move_and_slide()
	pass

# 获得exp
func getExp(point:int):
	stats.curExp+=point*stats.expRate

# 受伤
func getHurt():
	hurting=true
	stats.hp-=attacks[0].damage
	flash()
	await get_tree().create_timer(0.2).timeout
	hurting=false
	
# 闪烁 
func flash():
	$AnimatedSprite2D.material.set_shader_parameter('flashOpacity',1)
	await get_tree().create_timer(0.1).timeout
	$AnimatedSprite2D.material.set_shader_parameter('flashOpacity',0)

# 死亡
func die()->void:
	$AnimatedSprite2D.material.set_shader_parameter('flashOpacity',0)
	get_tree().reload_current_scene()

# --------------------事件信号----------------------#
# 鼠标在人物上停止
func _on_stop_mouse_entered() -> void:
	stop=true
func _on_stop_mouse_exited() -> void:
	stop=false

# 吸引物品
func _on_drop_area_entered(area:Area2D) -> void:
	if  area.is_in_group('dropItem'):
		area.canMove=true

# 拾取物品
func _on_stop_area_entered(area:Area2D) -> void:
	if  area.is_in_group('dropItem'):
		# 拾取金币
		if area is Gold:
			stats.gold+=stats.goldRate
		area.queue_free()

# 进入敌人攻击区域
func _on_stop_body_entered(body:Node2D) -> void:
	if body is Enemy:
		attacks.append(body)

# 脱离敌人
func _on_stop_body_exited(body:Node2D) -> void:
	if body is Enemy:
		attacks.erase(body)

